<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片部分 -->
    <el-card class="box-card">
      <!-- gutter表示两列之间的间隙 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="shuru">
            <el-button slot="append" icon="el-icon-search"
            @click="getUserLists" ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addvisible=true"
          
          >添加用户</el-button>
        </el-col>
      </el-row>
      <!-- border给表格添加边框线 stripe隔行变色效果  typr=index给表格添加序号-->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="\"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 使用作用域插槽  自我理解是把这里遍历的数组赋给这个标签-->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="getchange(scope.row)" active-color="#3F86D8" inactive-color="#E9EDF1"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="amend(scope.row)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletes(scope.row)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配管理" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
        <!-- 分页部分 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="400">
    </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <!-- @close表示退出对话框重置1 -->
<el-dialog
  title="添加用户"
  :visible.sync="addvisible"
  width="50%"
  @close="formdelete"
 >
 <!-- 主体内容 -->
 <!-- @close表示关闭表单的时候 -->
 <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px"
  >
  <el-form-item label="姓名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
  <el-form-item label="电话" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
   <el-form-item label="角色" prop="role_name">
    <el-input v-model="addForm.role_name"></el-input>
  </el-form-item>
 </el-form>
 <!-- 底部区域 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="addvisible = false">取 消</el-button>
    <el-button type="primary" @click="addv">确 定</el-button>
  </span>
  </el-dialog>
  <!-- 修改用户对话框 -->
  <el-dialog
  title="修改信息"
  :visible.sync="amends"
  width="50%"
   @close="amendsdelete"
  >
  <el-form :model="amendlist" :rules="amendlistrules" ref="amendlistForm" label-width="100px" >
  <el-form-item label="姓名" prop="username">
    <el-input v-model="amendlist.username" disabled></el-input>
  </el-form-item>
   <el-form-item label="邮箱" prop="email">
    <el-input v-model="amendlist.email"></el-input>
  </el-form-item>
   <el-form-item label="电话" prop="mobile">
    <el-input v-model="amendlist.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="amends = false">取 消</el-button>
    <el-button type="primary" @click="amen">确 定</el-button>
  </span>
</el-dialog>
 </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱验证
   var checkEmail=(rule,value,callback)=>{
      const resEmail=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if(resEmail.test(value)) return callback() 

      // 输入错误
      callback(new Error("请输入正确格式的邮箱"))
      console.log(rule)
   }
   var checkMobile=(rule,value,callback)=>{
     const resMoblie=/^1[3456789]\d{9}$/
   if(resMoblie.test(value)) return callback() 

    //  格式错误
      callback(new Error("手机号码格式错误"))
   }
    return {
      queryInfo: {
        query: "",
        // 页数
        pagenum: 1,
        // 每页显示的数量
        pagesize: 2  
      },
      userlist: [],
      amendlist:{},
      total: 0,
      shuru:"",
      // 对话框按钮
      addvisible:false,
      // 添加用户对话框
      addForm:{
        usersname:"",
        email:"",
        mobile:"",
        role_name:""
      },
      addFormrules:{
            //验证用户名是否合法
                username:[
                    // required表示必填项，message表示输入错误的时候报错信息，trigger表示失去焦点触发事件
                    { required: true, message: '请输入正确的用户名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                 email:[
                    // required表示必填项，message表示输入错误的时候报错信息，trigger表示失去焦点触发事件
                    { validator:checkEmail, trigger: 'blur' },
                    // { min: 8, max: 16, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                 mobile:[
                    // required表示必填项，message表示输入错误的时候报错信息，trigger表示失去焦点触发事件
                    { validator:checkMobile, trigger: 'blur' },   
                ],
                 role_name:[
                    // required表示必填项，message表示输入错误的时候报错信息，trigger表示失去焦点触发事件
                    { required: true, message: '请输入正确的角色身份', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
      },
      // 修改用户信息对话框显示影藏
      amends:false,
      // 验证规则
      amendlistrules:{
             email:[
                    // required表示必填项，message表示输入错误的时候报错信息，trigger表示失去焦点触发事件
                   { validator:checkEmail, trigger: 'blur' },
                    // { min: 8, max: 16, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                 mobile:[
                    // required表示必填项，message表示输入错误的时候报错信息，trigger表示失去焦点触发事件
                    { validator:checkMobile, trigger: 'blur' },   
                ],
      },
     
    };
  },
  created() {
    this.getUserList();
    //  this.getUserLists();
  },
  methods: {
     //   搜索处方法
       async getUserLists(userlist,shuru) {
       const { data: res } = await this.$http.get("yh", {
       params: this.queryInfo
      })
      var  use = res.users;
      return  userlist =use.filter(function(item){
             return item.usernam.match(shuru)
         })
       },
    //   渲染数据
    async getUserList() {
      const { data: res } = await this.$http.get("yh", {
        params: this.queryInfo
      });
  
      if (res.meta.status !== 200) {
        return this.$massage.error("获取用户列表失败!");
      }
      this.userlist = res.users;
      this.total = res.total;
    },
    handleSizeChange(n){
      console.log(n)
     this.queryInfo.pagesize = n
     this.getUserList()
    },
    handleCurrentChange(m){
        console.log(m)
     this.queryInfo.pagenum = m
     this.getUserList()
    },
    // 监听switvh开关状态的改变
  getchange(userlist){
    //       console.log(userlist)
    // const {data:res} = await this.$http.put(`
    // yh
    // `)
    // if(res.meta.status!==200){
        this.userlist.mg_state = !this.userlist.mg_state
        // this.$massage.success("更新用户状态成功")
         this.$message.success("修改成功") 
    //     return this.$massage.error('更新用户状态失败')
    // }
    //  userlist.mg_state = !userlist.mg_state
    // this.$massage.success('更新用户状态成功')
    },
    // 清除表单信息
    formdelete(){
      // 重置表单
      this.$refs.addFormRef.resetFields()
  },
  addv(){
    this.$refs.addFormRef.validate(valid=>{
      if(!valid) return
      // 可以添加信息了
      // this.$http.put("users",this.addForm)
      //  .then(res=>{
      //    console.log(res)
      //  })
      var fro={
        username:this.addForm.username,
        email:this.addForm.email,
        mobile:this.addForm.mobile,
        role_name:this.addForm.role_name
      }
     this.userlist.push(fro)
     this.addvisible=false
    })
  },
  amend(id){
   this.amends=true
  //  console.log(id)
   this.amendlist=id
  },
   // 重置保单
  amendsdelete(){
    this.$refs.amendlistForm.resetFields()
  },
  // 修改信息
  amen(){
    this.$refs.amendlistForm.validate(valid=>{
      if(!valid) return
      // console.log(this.userlist)
    var th=this.userlist.map(v=>{
    
       if(v.id==this.amendlist.id) {
        //  console.log(this.amendlist)
          return v={
              username:this.amendlist.username,
              email:this.amendlist.email,
              mobile:this.amendlist.mobile,
              role_name:this.amendlist.role_name
          }
          //  email=this.amendlist.email,
          //  v.mobile=this.amendlist.mobile,
          
          //  console.log(v.mobile)     
       }
     })
    // 修改数据
    this.userlist.splice(this.amendlist.id-1,th)
    //  console.log(this.userlist)
     this.amends=false
    
    })
  },
  // 删除数据
 async deletes(id){
   var res=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        console.log(res)
        if(res!=='confirm') return this.$message.info("取消删除");
         this.userlist.splice(id.id-1,1)
  }
  }
};
</script>

<style lang="less" scoped>
</style>